#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

  struct ListNode {
      int val;
      ListNode *next;
      ListNode() : val(0), next(nullptr) {}
     ListNode(int x) : val(x), next(nullptr) {}
     ListNode(int x, ListNode *next) : val(x), next(next) {}
  };
 
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        ListNode* head = nullptr;
        ListNode* tail = nullptr;
        int add = 0;
        while (l1 || l2 || add != 0)
        {
            int a = l1 ? l1->val : 0;
            int b = l2 ? l2->val : 0;
            int sum = a + b + add;
            if (sum >= 10)
            {
                add = 1;
                sum %= 10;
            }
            else
            {
                add = sum / 10;
            }
            if (!head)
            {
                head = tail = new ListNode(sum);
            }
            else
            {
                tail->next = new ListNode(sum);
                tail = tail->next;
            }
            if (l1) l1 = l1->next;
            if (l2) l2 = l2->next;
        }
        return head;
    }
};

//void main()
//{
//
//}